package com.agileai.portal.controller.forum;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.core.ResourceUploadService;
import com.agileai.hotweb.controller.core.FileUploadHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.forum.UserLevel8BBSUserInfoManage;
import com.agileai.portal.bizmoduler.wcm.WcmGeneralGroup8ContentManage;
import com.agileai.util.ListUtil;

public class ForumUserProfileResouceUploaderHandler
        extends FileUploadHandler {
	
    private static final String ResourceGroupId = "30ED6BC0-BFC2-4EA4-94FC-856C137D0119";

    public ForumUserProfileResouceUploaderHandler() {
        super();
    }
    public ViewRenderer prepareDisplay(DataParam param) {
        String grpId = ResourceGroupId;
        WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
        DataParam queryParam = new DataParam("GRP_ID", grpId);
        DataRow row = resourseManage.queryTreeRecord(queryParam);
        String resTypeDesc = row.stringValue("GRP_RES_TYPE_DESC");
        String resTypeExts = row.stringValue("GRP_RES_TYPE_EXTS");
        String resSizeLimit = row.stringValue("GRP_RES_SIZE_LIMIT");

        this.setAttribute("BIZ_ID", param.get("BIZ_ID"));
        this.setAttribute("GRP_ID", grpId);
        this.setAttribute("GRP_RES_TYPE_DESC", resTypeDesc);
        this.setAttribute("GRP_RES_TYPE_EXTS", resTypeExts);
        this.setAttribute("GRP_RES_SIZE_LIMIT", resSizeLimit);

        return new LocalRenderer(getPage());
    }

    @SuppressWarnings("rawtypes")
    @PageAction
    public ViewRenderer uploadFile(DataParam param) {
        String responseText = FAIL;
        String location =null;
        String bizId =null;
        try {
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload fileFileUpload = new ServletFileUpload(fac);
            fileFileUpload.setHeaderEncoding("utf-8");

            List fileList = null;
            fileList = fileFileUpload.parseRequest(request);

            Iterator it = fileList.iterator();
            String name = "";
            String fileFullPath = null;
            File filePath = this.buildResourseSavePath(ResourceGroupId);

            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();

                    if (fieldName.equals("BIZ_ID")) {
                        bizId = item.getString();
                        resourceParam.put("BIZ_ID", bizId);
                    }

                    continue;
                }

                name = item.getName();
                resourceParam.put("GRP_ID", ResourceGroupId);
                resourceParam.put("RES_NAME", name);
                
                String suffix = name.substring(name.lastIndexOf("."));
                String enName = KeyGenerator.instance().genShortKey() + suffix;
                
                location = resourceRelativePath + "/" + enName;
                resourceParam.put("RES_LOCATION", location);
                fileFullPath = filePath.getAbsolutePath() + File.separator + enName;
                setAttribute("location",location);
                long resourceSize = item.getSize();
                resourceParam.put("RES_SIZE", String.valueOf(resourceSize));

                resourceParam.put("RES_SUFFIX", suffix);
                resourceParam.put("RES_SHAREABLE", "Y");

                File tempFile = new File(fileFullPath);

                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }

                item.write(tempFile);
                this.insertResourceRecord();
            }
            DataParam updateParam = new DataParam("FU_ID",bizId,"FU_PROFILE",location);
            UserLevel8BBSUserInfoManage userLevel8BBSUserInfoManage = this.lookupService(UserLevel8BBSUserInfoManage.class);
            userLevel8BBSUserInfoManage.updateUserProfile(updateParam);
            responseText = SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new AjaxRenderer(responseText);
    }

    @PageAction
    public ViewRenderer delResource(DataParam param) {
    	this.serviceId = buildServiceId(UserLevel8BBSUserInfoManage.class);
        String responseText = FAIL;
        try {
            String refId = param.get("REL_ID")+",";
            String bizId = param.get("BIZ_ID");
            ResourceUploadService resourceUploadService = getResourceUploadService();
            List<String> refIdList = new ArrayList<String>();
            String[] refIds = refId.split(",");
            ListUtil.addArrayToList(refIdList, refIds);
            resourceUploadService.deleteResourceRelations(refIdList);
            DataParam updateParam = new DataParam("FU_ID",bizId,"FU_PROFILE",""); 
            UserLevel8BBSUserInfoManage userLevel8BBSUserInfoManage = this.lookupService(UserLevel8BBSUserInfoManage.class);
            userLevel8BBSUserInfoManage.updateUserProfile(updateParam);
            responseText = SUCCESS;
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
        return new AjaxRenderer(responseText);
    }

    @PageAction
    public ViewRenderer loadResourceList(DataParam param) {
    	this.serviceId = buildServiceId(UserLevel8BBSUserInfoManage.class);
        String responseText = FAIL;
        String bizId = param.get("BIZ_ID");
        try {
            ResourceUploadService resourceUploadService = getResourceUploadService();
            DataParam queyrParam = new DataParam("BIZ_ID", bizId);
            List<DataRow> records = resourceUploadService.findResourceRelations(queyrParam);
            if ((records != null) && (records.size() > 0)) {
                JSONArray jsonArray = new JSONArray();

                for (int i = 0; i < 1; i++) {
                    JSONObject jsonObject = new JSONObject();
                    DataRow row = records.get(i);
                    String resId = row.stringValue("RES_ID");
                    DataRow record = getService().getResLocation(resId);
                    String dataText = record.getString("RES_LOCATION");
                    String dataValue = row.stringValue("REL_ID");
                    jsonObject.put("text", dataText);
                    jsonObject.put("value", dataValue);
                    jsonArray.put(jsonObject);
                }
                responseText = jsonArray.toString();
            }
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }

        return new AjaxRenderer(responseText);
    }

	private void insertResourceRecord() {
        WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
        resourseManage.createtContentRecord("WcmGeneralResource", resourceParam);

        String resId = resourceParam.get("RES_ID");
        String bizId = resourceParam.get("BIZ_ID");
        ResourceUploadService resourceUploadService = getResourceUploadService();
        resourceUploadService.createResourceRelation(bizId, resId);
    }

    private ResourceUploadService getResourceUploadService() {
        return (ResourceUploadService) this.lookupService("forumUserProfileResouceUploaderService");
    }
    protected UserLevel8BBSUserInfoManage getService() {
        return (UserLevel8BBSUserInfoManage) this.lookupService(this.getServiceId());
    }
}
